package com.ktgj.customer.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.IDCardUtil;
import com.ktgj.common.core.utils.Pinyin4jUtil;
import com.ktgj.common.core.utils.SnowflakeUtils;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.back.CommonTravelersBack;
import com.ktgj.customer.domain.back.PassengerDocumentsBack;
import com.ktgj.customer.domain.vo.*;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.ICustomeraccountService;
import com.ktgj.customer.service.ILoginService;
import com.ktgj.customer.util.ChineseCharacterUtil;
import com.ktgj.customer.vo.ClassificationVo;
import com.ktgj.customer.vo.CountryDetailsVo;
import com.ktgj.customer.vo.NationVo;
import com.ktgj.train.api.RemoteTrainService;
import com.ktgj.train.api.domain.TrContactQueryRequestApi;
import com.ktgj.train.api.domain.TrContactQueryResponseApi;
import com.ktgj.train.api.domain.TrainAccountApi;
import com.ktgj.train.api.domain.TrainContactsApi;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.customer.service.ICommonTravelersService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 常用旅客信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-09-01
 */
@Service
public class CommonTravelersServiceImpl implements ICommonTravelersService 
{
    @Autowired
    private CommonTravelersMapper commonTravelersMapper;
    @Autowired
    private PassengerDocumentsMapper passengerDocumentsMapper;
    @Autowired
    private NationMapper nationMapper;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ICustomeraccountService customeraccountService;
    @Autowired
    private RemoteTrainService remoteTrainService;



    /**
     * 查询常用旅客信息
     *
     * @param commonTrvelersId 常用旅客信息ID
     * @return 常用旅客信息
     */
    @Override
    public CommonTravelers selectCommonTravelersById(Long commonTrvelersId)
    {
        return commonTravelersMapper.selectCommonTravelersById(commonTrvelersId);
    }

    /**
     * 查询常用旅客信息列表
     * 
     * @param commonTravelers 常用旅客信息
     * @return 常用旅客信息
     */
    @Override
    public List<CommonTravelers> selectCommonTravelersList(CommonTravelers commonTravelers)
    {
        return commonTravelersMapper.selectCommonTravelersList(commonTravelers);
    }

    /**
     * 新增常用旅客信息
     * 
     * @param commonTravelers 常用旅客信息
     * @return 结果
     */
    @Override
    public int insertCommonTravelers(CommonTravelers commonTravelers)
    {
        return commonTravelersMapper.insertCommonTravelers(commonTravelers);
    }

    /**
     * 修改常用旅客信息
     * 
     * @param commonTravelers 常用旅客信息
     * @return 结果
     */
    @Override
    public int updateCommonTravelers(CommonTravelers commonTravelers)
    {
        return commonTravelersMapper.updateCommonTravelers(commonTravelers);
    }

    /**
     * 批量删除常用旅客信息
     * 
     * @param commonTrvelersIds 需要删除的常用旅客信息ID
     * @return 结果
     */
    @Override
    public int deleteCommonTravelersByIds(Long[] commonTrvelersIds)
    {
        return commonTravelersMapper.deleteCommonTravelersByIds(commonTrvelersIds);
    }

    /**
     * 删除常用旅客信息信息
     * 
     * @param commonTrvelersId 常用旅客信息ID
     * @return 结果
     */
    @Override
    public int deleteCommonTravelersById(Long commonTrvelersId)
    {
        return commonTravelersMapper.deleteCommonTravelersById(commonTrvelersId);
    }

    /**
     * 新增旅客信息
     * */
    @Override
    @Transactional
    public int saveCommonTravelersByMemberId(CommonTravelersVo commonTravelersVo) {
        int count = 0;
        CommonTravelersDtos commonTravelersDtos = new CommonTravelersDtos();
        if (commonTravelersVo.getChineseName() != null && !commonTravelersVo.getChineseName().equals("")){
            commonTravelersDtos.setChineseName(commonTravelersVo.getChineseName());
        }
        if (commonTravelersVo.getEnglishSurname() != null && !commonTravelersVo.getEnglishSurname().equals("") &&
                commonTravelersVo.getEnglishName() != null && !commonTravelersVo.getEnglishName().equals("")){
            commonTravelersDtos.setEnglishSurname(commonTravelersVo.getEnglishSurname());
            commonTravelersDtos.setEnglishName(commonTravelersVo.getEnglishName());
        }
        commonTravelersDtos.setGender(commonTravelersVo.getGender());
        commonTravelersDtos.setDateOfBirth(commonTravelersVo.getDateOfBirth());
        commonTravelersDtos.setDomesticPhone(commonTravelersVo.getDomesticPhone());
        commonTravelersDtos.setWhetherTravelerInformation(commonTravelersVo.getWhetherTravelerInformation());
        commonTravelersDtos.setMemberId(commonTravelersVo.getMemberId());
        commonTravelersDtos.setIsDeletes("false");

        Nation nation = nationMapper.selectNationByNationName(commonTravelersVo.getNationName());

        commonTravelersDtos.setNationId(nation.getNationId());
//        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
//        long nextId = snowflakeUtils.nextId();
//        commonTravelersDtos.setCommonTrvelersId(nextId);
        commonTravelersDtos.setTicketType(age(commonTravelersVo.getDateOfBirth()));
        int commonTravelersNum = commonTravelersMapper.insertCommonTravelersByMemberId(commonTravelersDtos);

        Long commonTrvelersId = commonTravelersDtos.getCommonTrvelersId();
        PassengerDocuments passengerDocumentsList = commonTravelersVo.getPassengerDocumentsList();
        passengerDocumentsList.setCommontrvelersId(commonTrvelersId);
        int passengerDocumentsNum = passengerDocumentsMapper.insertPassenger(passengerDocumentsList);
        if (commonTravelersNum > 0 && passengerDocumentsNum > 0){
            count = 1;
        }
        return count;
    }

    /**
     * 判断指定出生日期为成人/儿童（成人>12 儿童 2-12 婴儿暂不管）——机票专用
     * */
    public String age(Date dateOfBirth){
        Calendar cal = Calendar.getInstance();
        //出生日期晚于当前时间，无法计算
        if (cal.before(dateOfBirth)) {
            throw new IllegalArgumentException("出生日期不能晚于当前时间");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(dateOfBirth);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            }else{
                age--;//当前月份在生日之前，年龄减一
            }
        }
        if (age > 12){
            return "aldult";
        }
        else if (age > 2 && age <= 12){
            return "child";
        }
        else {
            return "baby";
        }
    }

    /**
     * 查询国家列表
     * */
    @Override
    public NationVo selectNationVo(String nationName) throws Exception {
        String[] letterList = {"热门", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        NationVo nationVo = new NationVo();
        List<ClassificationVo> classificationVoList = new ArrayList<>();

        List<Nation> nationList;

        if (nationName != null && !nationName.equals("")){
            nationList = nationMapper.selectNationLike("%"+nationName+"%");//模糊
        }
        else {
            nationList = nationMapper.selectNationLike("%%");//模糊
        }

        if (nationList.size() > 0){
            for (int i = 0 ; i < letterList.length ; ++i){
                ClassificationVo classificationVo = new ClassificationVo();
                classificationVo.setLetter(letterList[i]);
                List<CountryDetailsVo> countryDetailsVoList = new ArrayList<>();
                for (Nation nation : nationList) {
                    String pinYinHeadChar = getPinYinHeadChar(nation.getNationName()).substring(0, 1);//获取国家首字母
                    if ((letterList[i].equals(pinYinHeadChar)) ||
                            (letterList[i].equals("热门") && nation.getPopular().equals("true"))){
                        CountryDetailsVo countryDetailsVo = new CountryDetailsVo();
                        countryDetailsVo.setNationId(nation.getNationId());
                        countryDetailsVo.setNationName(nation.getNationName());
                        countryDetailsVo.setPopular(nation.getPopular());
                        countryDetailsVo.setInitials(pinYinHeadChar);
                        countryDetailsVo.setCountryCode(nation.getCountryCode());
                        countryDetailsVoList.add(countryDetailsVo);
                    }
                }
                classificationVo.setCountryDetailsVoList(countryDetailsVoList);
                if (classificationVo.getCountryDetailsVoList().size() > 0){//去除空集合
                    classificationVoList.add(classificationVo);
                }
            }
            nationVo.setClassificationVoList(classificationVoList);
        }
        else {
            throw new Exception("未查询到国家信息");
        }
        return nationVo;
    }

    /**
     * 查询待编辑的常用旅客信息
     * */
    @Override
    public CommonTravelersVo selectPassengerInformation(Long commonTrvelersId, Long customerId) {
        CommonTravelers commonTravelers = commonTravelersMapper.selectPassengerInformation(commonTrvelersId);
        CommonTravelersVo commonTravelersVo = new CommonTravelersVo();
        commonTravelersVo.setMemberId(customerId);
        commonTravelersVo.setChineseName(commonTravelers.getChineseName());
        commonTravelersVo.setEnglishSurname(commonTravelers.getEnglishSurname());
        commonTravelersVo.setEnglishName(commonTravelers.getEnglishName());
        if (commonTravelers.getGender() != null && commonTravelers.getGender().equals("male")){
            commonTravelersVo.setGender("男");
        }
        else if (commonTravelers.getGender() != null && commonTravelers.getGender().equals("female")){
            commonTravelersVo.setGender("女");
        }
        commonTravelersVo.setDateOfBirth(commonTravelers.getDateOfBirth());
        Nation nation = nationMapper.selectNationByNationId(commonTravelers.getNationId());
        if (nation != null)
            commonTravelersVo.setNationName(nation.getNationName());
        commonTravelersVo.setDomesticPhone(commonTravelers.getDomesticPhone());
        commonTravelersVo.setWhetherTravelerInformation(commonTravelers.getWhetherTravelerInformation());
        PassengerDocuments passengerDocuments = passengerDocumentsMapper.queryPassengerDocumentsByCommontrvelersId(commonTrvelersId);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (passengerDocuments != null) {
            if (passengerDocuments.getIsDelete().equals("false") && passengerDocuments.getCertificateDate() != null && !passengerDocuments.getCertificateDate().equals("")){
                Date date = new Date();
                Date certificateDate = null;
                try {
                    certificateDate = format.parse(passengerDocuments.getCertificateDate());
                }catch (Exception e){
                    e.printStackTrace();
                }

                int compareTo = certificateDate.compareTo(date);

                if (compareTo == 1){
                    boolean boo = dayTime(passengerDocuments.getCertificateDate());
                    if (boo){
                        passengerDocuments.setValidPeriod("willExpireSoon");
                    }
                    else {
                        passengerDocuments.setValidPeriod("true");
                    }
                }
                else {
                    passengerDocuments.setValidPeriod("false");
                }
            }
        }

        commonTravelersVo.setPassengerDocumentsList(passengerDocuments);
        return commonTravelersVo;
    }

    /**
     * 修改常用旅客信息
     * */
    @Override
    public int modifyPassenger(CommonTravelersVo commonTravelersVo) throws Exception {
        int count = 0;
        Nation nation = nationMapper.selectNationByNationName(commonTravelersVo.getNationName());
        //修改旅客信息
        CommonTravelers commonTravelers = new CommonTravelers();
        commonTravelers.setCommonTrvelersId(commonTravelersVo.getCommonTrvelersId());
        if (commonTravelersVo.getChineseName() != null && !commonTravelersVo.getChineseName().equals("")){
            commonTravelers.setChineseName(commonTravelersVo.getChineseName());
        }
        if (commonTravelersVo.getEnglishSurname() != null && !commonTravelersVo.getEnglishSurname().equals("") &&
                commonTravelersVo.getEnglishSurname() != null && !commonTravelersVo.getEnglishSurname().equals("")){
            commonTravelers.setEnglishSurname(commonTravelersVo.getEnglishSurname());
            commonTravelers.setEnglishName(commonTravelersVo.getEnglishName());
        }
        commonTravelers.setGender(commonTravelersVo.getGender());
        commonTravelers.setDateOfBirth(commonTravelersVo.getDateOfBirth());
        commonTravelers.setDomesticPhone(commonTravelersVo.getDomesticPhone());
        commonTravelers.setWhetherTravelerInformation(commonTravelersVo.getWhetherTravelerInformation());
        commonTravelers.setNationId(nation.getNationId());
        int commonTravelersCount = commonTravelersMapper.updateCommonTravelersByMemberId(commonTravelers);

        //获取旅客的全部证件集合
        List<PassengerDocuments> temporaryPassengerDocuments = passengerDocumentsMapper.selectPassengerDocumentsByCommontrvelersId(commonTravelersVo.getCommonTrvelersId());

        if (commonTravelersVo.getPassengerDocumentsList() != null) {
            PassengerDocuments passengerDocuments = commonTravelersVo.getPassengerDocumentsList();
            String mark = null;
            for (PassengerDocuments temporaryPassengerDocument : temporaryPassengerDocuments) {
                if (passengerDocuments.getPassengerDocumentsId() == null) {
                    //新增
                    mark = "insert";
                } else if (temporaryPassengerDocument.getPassengerDocumentsId().equals(passengerDocuments.getPassengerDocumentsId())) {
                    //修改
                    mark = "update";
                    temporaryPassengerDocument.setValidPeriod("true");
                }
            }

            if (mark.equals("update")) {
                PassengerDocuments certificate = new PassengerDocuments();
                certificate.setPassengerDocumentsId(passengerDocuments.getPassengerDocumentsId());
                certificate.setCertificateType(passengerDocuments.getCertificateType());
                certificate.setCertificateName(passengerDocuments.getCertificateName());
                certificate.setCertificateNumcer(passengerDocuments.getCertificateNumcer());
                certificate.setCertificateDate(passengerDocuments.getCertificateDate());
                int passengerDocumentsCount = passengerDocumentsMapper.updatePassengerDocuments(certificate);
                if (passengerDocumentsCount <= 0) {
                    count = 2;
                }
            } else if (mark.equals("insert")) {
                List<PassengerDocuments> passengerDocumentsList = new ArrayList<>();
                passengerDocuments.setCommontrvelersId(commonTravelersVo.getCommonTrvelersId());
                passengerDocumentsList.add(passengerDocuments);
                int insert = passengerDocumentsMapper.insertPassengerDocuments(passengerDocumentsList);
                if (insert <= 0) {
                    count = 2;
                }
            }
        } else {
            throw new Exception("证件信息不能为空！");
        }

        for (PassengerDocuments temporaryPassengerDocument : temporaryPassengerDocuments) {
            if (temporaryPassengerDocument.getValidPeriod() == null){
                int delete = passengerDocumentsMapper.updatePassengerDocumentsIsDelete(temporaryPassengerDocument.getPassengerDocumentsId());
                if (delete <= 0){
                    count = 2;
                }
            }
        }

        if (commonTravelersCount > 0 && count != 2){
            count = 1;
        }
        return count;
    }

    @Override
    public List<CommonPassenger> queryPassengerByCustomerId(Long customerId, Long commonTrvelersId, String certificateType) {
        return commonTravelersMapper.queryPassengerByCustomerId(customerId, commonTrvelersId, certificateType);
    }

    /**
     * 获取中文首字母
     * */
    public static String getPinYinHeadChar(String str) {
        StringBuilder convert = new StringBuilder();
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        String toUpperCase = convert.toString().toUpperCase();
        return toUpperCase;
    }

    /**
     * 获取当前时间的后7个月时间并校验任意时间是否在该时间段内
     * */
    public boolean dayTime(String eTime){
        GregorianCalendar now = new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        now.add(GregorianCalendar.MONTH, 7);
        String l = sdf.format(now.getTime());
        if (eTime.compareTo(l) <= 0){
            return true;
        }
        return false;
    }

    @Override
    public CommonTravelersDto queryByCustomerIdCommon(Long customerId) {
        return commonTravelersMapper.queryByCustomerIdCommon(customerId);
    }

    /**
     * 删除常用旅客信息
     * */
    @Transactional
    @Override
    public int tombstone(Long commonTrvelersId, Long customerId) throws Exception {
        int count;
        int tombstone = commonTravelersMapper.tombstone(commonTrvelersId, customerId);
        List<PassengerDocuments> passengerDocuments = passengerDocumentsMapper.selectDocumentsByCommontrvelersId(commonTrvelersId);
        int tombstoneCertificate = passengerDocumentsMapper.tombstoneCertificate(commonTrvelersId);
        if (tombstone > 0){
            if (passengerDocuments != null && passengerDocuments.size() > 0 && tombstoneCertificate == 0){
                throw new Exception("删除证件时出现异常");
            }
            count = 1;
        }
        else {
            throw new Exception("删除失败");
        }
        return count;
    }

    /**
     * 查询会员全部常用旅客
     * */
    @Override
    public LetterVo generalInformation(Long memberId) {
        String[] letterList = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

        List<CommonTravelers> commonTravelersList = commonTravelersMapper.selectCommonTravelersByMemberId(memberId);
        Customer customer = customerMapper.certificate(memberId);

        LetterVo letterVo = new LetterVo();
        ChineseCharacterUtil chineseCharacterUtil = new ChineseCharacterUtil();
        List<CTravelers> cTravelersList = new ArrayList<>();


        if (commonTravelersList.size() > 0){//查询结果不为null

            for (int i = 0 ; i < letterList.length ; i++) {//遍历字母数组

                List<CTravelersVo> cTravelersVoList = new ArrayList<>();
                CTravelers cTravelers = new CTravelers();
                cTravelers.setLetter(letterList[i]);

                for (CommonTravelers commonTravelers : commonTravelersList) {//遍历会员全部旅客信息
                    if (commonTravelers.getIsDeletes().equals("false")){//排除已删除旅客

                        String pinYinHeadChar = getPinYinHeadChar(commonTravelers.getChineseName()).substring(0, 1);//获取首字母

                        if (pinYinHeadChar.equals(letterList[i])){//字母匹对

                            CTravelersVo cTravelersVo = new CTravelersVo();
                            cTravelersVo.setCTravelersVoId(commonTravelers.getCommonTrvelersId());
                            cTravelersVo.setChineseName(commonTravelers.getChineseName());
                            cTravelersVo.setChineseFullFight(chineseCharacterUtil.convertHanzi2Pinyin(commonTravelers.getChineseName()).toUpperCase());
                            cTravelersVo.setMyself("false");

                            PassengerDocuments passengerDocument = passengerDocumentsMapper.queryPassengerDocumentsByCommontrvelersId(commonTravelers.getCommonTrvelersId());

                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

                            if (passengerDocument != null){//查询结果不为null
                                CertificateDto certificateDto = new CertificateDto();
                                if (passengerDocument.getIsDelete().equals("false")){//排除已删除证件
                                    if (passengerDocument.getCertificateType().equals("ID_CARD") &&
                                            passengerDocument.getCertificateNumcer().equals(customer.getCustCertificateNo())){
                                        cTravelersVo.setMyself("true");
                                    }

                                    Date date = new Date();
                                    Date certificateDate = null;
                                    int compareTo = 0;

                                    if (passengerDocument.getCertificateDate()!=null)
                                    {
                                        try
                                        {
                                            certificateDate = format.parse(passengerDocument.getCertificateDate());
                                            compareTo = certificateDate.compareTo(date);
                                        } catch (ParseException e)
                                        {
                                            e.printStackTrace();
                                        }
                                    }
                                    if (compareTo == 1){//判断证件有效期并给予提示
                                        boolean boo = dayTime(passengerDocument.getCertificateDate());
                                        if (boo){
                                            certificateDto.setCertificateRemind("willExpireSoon");
                                        }
                                        else {
                                            certificateDto.setCertificateRemind("true");
                                        }
                                    }
                                    else {
                                        certificateDto.setCertificateRemind("false");
                                    }
                                    certificateDto.setCertificateId(passengerDocument.getPassengerDocumentsId());
                                    certificateDto.setCertificateName(passengerDocument.getCertificateName());
                                    certificateDto.setCertificatePhone(passengerDocument.getCertificateNumcer());
                                    certificateDto.setCertificateType(passengerDocument.getCertificateType());
                                    cTravelersVo.setCertificateDtoList(certificateDto);
                                }
                            }
                            cTravelersVo.setTravelerId(cTravelersVo.getCTravelersVoId().toString());
                            cTravelersVoList.add(cTravelersVo);
                        }
                    }
                }

                cTravelers.setcTravelersVoList(cTravelersVoList);
                if (cTravelers.getcTravelersVoList().size() > 0){//当字母集合未空时去除
                    cTravelersList.add(cTravelers);
                }
            }
        }
        else {
            return null;
        }
        letterVo.setcTravelersList(cTravelersList);
        return letterVo;
    }

    /**
     * 会员常用旅客信息列表（远程）
     * */
    @Override
    public List<CustomerTraveler> CustomerTravelerList(Long memberId) {
        List<CommonTravelers> travelersList = commonTravelersMapper.selectCommonTravelersByMemberId(memberId);

        List<CustomerTraveler> customerTravelerList = new ArrayList<>();
        for (CommonTravelers commonTravelers : travelersList) {
            if (commonTravelers.getIsDeletes().equals("false")){//去除已删除的旅客信息

                CustomerTraveler customerTraveler = new CustomerTraveler();
                customerTraveler.setTravelerId(commonTravelers.getCommonTrvelersId());

                if (commonTravelers.getNationId() == 51){//中国信息（旅客姓名为中文）
                    customerTraveler.setTravelerName(commonTravelers.getChineseName());
                }
                else {//非中国信息（旅客姓名为英文）例：英文名/英文姓
                    customerTraveler.setTravelerName(commonTravelers.getEnglishName()+"/"+commonTravelers.getEnglishSurname());
                }
                customerTravelerList.add(customerTraveler);
            }
        }
        return customerTravelerList;
    }

    @Override
    public int insertCommonTraveler(String token, PassengerInformation information) {
        Customer customer = loginService.getLoginCustomerByToken(token);
        List<PassengerDocuments> passengerDocuments = passengerDocumentsMapper.queryCertificateNumber(customer.getCustomerId());
        Nation nation = nationMapper.selectId(information.getNationality());
        if (passengerDocuments != null && passengerDocuments.size() > 0) {
            List list = new ArrayList();
            for (PassengerDocuments passengerDocument : passengerDocuments) {
                String certificateNumcer = passengerDocument.getCertificateNumcer();
                list.add(certificateNumcer);
            }
            String certificateNumcer = information.getPassengerDocuments().getCertificateNumcer();
            boolean contains = list.contains(certificateNumcer);
            if (!contains) {
                CommonTravelers commonTravelers = new CommonTravelers();
                SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
                PassengerDocuments documents = new PassengerDocuments();
                long nextId = snowflakeUtils.nextId();
                commonTravelers.setCommonTrvelersId(nextId);
                commonTravelers.setChineseName(information.getChineseName());
                if (information.getGender() != null && information.getGender() != "") {
                    commonTravelers.setGender(information.getGender());
                }
                if (information.getDateOfBirth() != null) {
                    commonTravelers.setDateOfBirth(information.getDateOfBirth());
                }
                //commonTravelers.setNationality(information.getNationality());
                commonTravelers.setDomesticPhone(information.getDomesticPhone());
                commonTravelers.setMemberId(customer.getCustomerId());
                if (nation != null) {
                    commonTravelers.setNationId(nation.getNationId());
                }
                commonTravelers.setTicketType(information.getTicketType());
                documents.setCommontrvelersId(nextId);
                documents.setCertificateType(information.getPassengerDocuments().getCertificateType());
                documents.setCertificateName(information.getPassengerDocuments().getCertificateName());
                documents.setCertificateNumcer(information.getPassengerDocuments().getCertificateNumcer());
                if (information.getPassengerDocuments().getCertificateDate() != null && information.getPassengerDocuments().getCertificateDate() != "") {
                    documents.setCertificateDate(information.getPassengerDocuments().getCertificateDate());
                }
                passengerDocumentsMapper.insertPassenger(documents);
                return commonTravelersMapper.insertCommonTravelers(commonTravelers);
            }
        } else {
            CommonTravelers commonTravelers = new CommonTravelers();
            SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
            long nextId = snowflakeUtils.nextId();
            commonTravelers.setCommonTrvelersId(nextId);
            commonTravelers.setChineseName(information.getChineseName());
            if (information.getGender() != null && information.getGender() != "") {
                commonTravelers.setGender(information.getGender());
            }
            if (information.getDateOfBirth() != null) {
                commonTravelers.setDateOfBirth(information.getDateOfBirth());
            }
            //commonTravelers.setNationality(information.getNationality());
            commonTravelers.setDomesticPhone(information.getDomesticPhone());
            commonTravelers.setMemberId(customer.getCustomerId());
            if (nation != null) {
                commonTravelers.setNationId(nation.getNationId());
            }
            commonTravelers.setTicketType(information.getTicketType());
            PassengerDocuments documents = new PassengerDocuments();
            documents.setCommontrvelersId(nextId);
            documents.setCertificateType(information.getPassengerDocuments().getCertificateType());
            documents.setCertificateName(information.getPassengerDocuments().getCertificateName());
            documents.setCertificateNumcer(information.getPassengerDocuments().getCertificateNumcer());
            if (information.getPassengerDocuments().getCertificateDate() != null && information.getPassengerDocuments().getCertificateDate() != "") {
                documents.setCertificateDate(information.getPassengerDocuments().getCertificateDate());
            }
            passengerDocumentsMapper.insertPassenger(documents);
            return commonTravelersMapper.insertCommonTravelers(commonTravelers);
        }
        return 0;
    }

    @Override
    public int insertCommonTravelerCrm(Long customerId, PassengerInformation information) {
        Customer customer = customerMapper.selectCustomerById(customerId);
        List<PassengerDocuments> passengerDocuments = passengerDocumentsMapper.queryCertificateNumber(customer.getCustomerId());
        Nation nation = nationMapper.selectId(information.getNationality());
        if (passengerDocuments != null && passengerDocuments.size() > 0) {
            List list = new ArrayList();
            for (PassengerDocuments passengerDocument : passengerDocuments) {
                String certificateNumcer = passengerDocument.getCertificateNumcer();
                list.add(certificateNumcer);
            }
            String certificateNumcer = information.getPassengerDocuments().getCertificateNumcer();
            boolean contains = list.contains(certificateNumcer);
            if (!contains) {
                CommonTravelers commonTravelers = new CommonTravelers();
                SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
                PassengerDocuments documents = new PassengerDocuments();
                long nextId = snowflakeUtils.nextId();
                commonTravelers.setCommonTrvelersId(nextId);
                commonTravelers.setChineseName(information.getChineseName());
                if (information.getGender() != null && information.getGender() != "") {
                    commonTravelers.setGender(information.getGender());
                }
                if (information.getDateOfBirth() != null) {
                    commonTravelers.setDateOfBirth(information.getDateOfBirth());
                }
                //commonTravelers.setNationality(information.getNationality());
                commonTravelers.setDomesticPhone(information.getDomesticPhone());
                commonTravelers.setMemberId(customer.getCustomerId());
                if (nation != null) {
                    commonTravelers.setNationId(nation.getNationId());
                }
                commonTravelers.setTicketType(information.getTicketType());
                documents.setCommontrvelersId(nextId);
                documents.setCertificateType(information.getPassengerDocuments().getCertificateType());
                documents.setCertificateName(information.getPassengerDocuments().getCertificateName());
                documents.setCertificateNumcer(information.getPassengerDocuments().getCertificateNumcer());
                if (information.getPassengerDocuments().getCertificateDate() != null && information.getPassengerDocuments().getCertificateDate() != "") {
                    documents.setCertificateDate(information.getPassengerDocuments().getCertificateDate());
                }
                passengerDocumentsMapper.insertPassenger(documents);
                return commonTravelersMapper.insertCommonTravelers(commonTravelers);
            }
        } else {
            CommonTravelers commonTravelers = new CommonTravelers();
            SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
            long nextId = snowflakeUtils.nextId();
            commonTravelers.setCommonTrvelersId(nextId);
            commonTravelers.setChineseName(information.getChineseName());
            if (information.getGender() != null && information.getGender() != "") {
                commonTravelers.setGender(information.getGender());
            }
            if (information.getDateOfBirth() != null) {
                commonTravelers.setDateOfBirth(information.getDateOfBirth());
            }
            //commonTravelers.setNationality(information.getNationality());
            commonTravelers.setDomesticPhone(information.getDomesticPhone());
            commonTravelers.setMemberId(customer.getCustomerId());
            if (nation != null) {
                commonTravelers.setNationId(nation.getNationId());
            }
            commonTravelers.setTicketType(information.getTicketType());
            PassengerDocuments documents = new PassengerDocuments();
            documents.setCommontrvelersId(nextId);
            documents.setCertificateType(information.getPassengerDocuments().getCertificateType());
            documents.setCertificateName(information.getPassengerDocuments().getCertificateName());
            documents.setCertificateNumcer(information.getPassengerDocuments().getCertificateNumcer());
            if (information.getPassengerDocuments().getCertificateDate() != null && information.getPassengerDocuments().getCertificateDate() != "") {
                documents.setCertificateDate(information.getPassengerDocuments().getCertificateDate());
            }
            passengerDocumentsMapper.insertPassenger(documents);
            return commonTravelersMapper.insertCommonTravelers(commonTravelers);
        }
        return 0;
    }

    //旅客列表
    @Override
    public List<PassengerList> passenger(String token) {
        ChineseCharacterUtil chineseCharacterUtil = new ChineseCharacterUtil();
        List<PassengerList> passengerLists = new ArrayList<>();
        Customer customer = loginService.getLoginCustomerByToken(token);
        List<CommonTravelers> travelers = commonTravelersMapper.queryCommonTravelersList(customer.getCustomerId());
        for (CommonTravelers traveler : travelers) {
            PassengerList passenger = new PassengerList();
            String nameFullPinyin = chineseCharacterUtil.convertHanzi2Pinyin(traveler.getChineseName()).toUpperCase();
            passenger.setChineseName(traveler.getChineseName());
            passenger.setTicketType(traveler.getTicketType());
            passenger.setNameFullPinyin(nameFullPinyin);
            Certificates certificates = new Certificates();
            certificates.setCertificateType(traveler.getDocuments().getCertificateType());
            certificates.setCertificateName(traveler.getDocuments().getCertificateName());
            certificates.setCertificateNumcer(traveler.getDocuments().getCertificateNumcer());
            passenger.setCertificates(certificates);
            passengerLists.add(passenger);
        }
        return passengerLists;
    }

    /**
     * 火车票-乘车人列表
     * */
    @Override
    public LetterDto passengerList(Long memberId, String phone) throws Exception {
        String[] letterList = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

        LetterDto letterDto = new LetterDto();
        List<SortVo> sortVoList = new ArrayList<>();

        if (memberId != null && memberId != 0){

            List<CommonTravelers> travelersList = commonTravelersMapper.passengerList(memberId);

            //获取会员12306账号信息
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", memberId);
            TrainAccountApi trainAccountApi = remoteTrainService.queryAccountIdCrm(map);

            TrContactQueryRequestApi contactQueryRequestApi = new TrContactQueryRequestApi();
            contactQueryRequestApi.trainAccount = trainAccountApi.getAccountId();
            contactQueryRequestApi.pass = trainAccountApi.getAccountPassword();

            TrContactQueryResponseApi trContactQueryResponseApi = remoteTrainService.contactQuerys(contactQueryRequestApi);

            if (!trContactQueryResponseApi.success){
                throw new Exception("未查询到12306乘车人信息");
            }

            if (travelersList != null && travelersList.size() > 0){

                for (int i = 0 ; i < letterList.length ; i++) {//遍历字母数组
                    SortVo sortVo = new SortVo();
                    List<CommonTravelersDtoVo> commonTravelersDtoVoList = new ArrayList<>();

                    for (CommonTravelers commonTravelers : travelersList) {
                        for (TrainContactsApi datum : trContactQueryResponseApi.data) {

                            if (commonTravelers.getIsDeletes().equals("false")){

                                String pinYinHeadChar = getPinYinHeadChar(commonTravelers.getChineseName()).substring(0, 1);
                                if (pinYinHeadChar == letterList[i] || pinYinHeadChar.equals(letterList[i])){
                                    CommonTravelersDtoVo commonTravelersDtoVo = new CommonTravelersDtoVo();
                                    PassengerDocuments passengerDocuments = passengerDocumentsMapper.queryPassengerDocumentsByCommontrvelersId(commonTravelers.getCommonTrvelersId());
                                    if (passengerDocuments.getCertificateNumcer()==null)
                                    {
                                        continue;
                                    }
                                    //数据库与12306乘车人比对
                                    if (passengerDocuments != null && !passengerDocuments.equals(null) &&
                                            passengerDocuments.getCertificateNumcer().substring(0, 4).equals(datum.getIdenty().substring(0, 4)) &&
                                            passengerDocuments.getCertificateNumcer().substring(passengerDocuments.getCertificateNumcer().length()-3).equals(datum.getIdenty().substring(datum.getIdenty().length()-3)) &&
                                            commonTravelers.getChineseName().equals(datum.getName())){
                                        PassengerDocumentsVo passengerDocumentsVo = new PassengerDocumentsVo();
                                        passengerDocumentsVo.setCertificateName(passengerDocuments.getCertificateName());
                                        passengerDocumentsVo.setCertificateNumcer(passengerDocuments.getCertificateNumcer());
                                        passengerDocumentsVo.setCertificateType(passengerDocuments.getCertificateType());
                                        passengerDocumentsVo.setCommontrvelersId(String.valueOf(commonTravelers.getCommonTrvelersId()));
                                        passengerDocumentsVo.setCertificateDate(passengerDocuments.getCertificateDate());

                                        commonTravelersDtoVo.setCommonTrvelersId(commonTravelers.getCommonTrvelersId().toString());
                                        commonTravelersDtoVo.setChineseName(commonTravelers.getChineseName());
                                        commonTravelersDtoVo.setEnglishSurname(commonTravelers.getEnglishSurname());
                                        commonTravelersDtoVo.setEnglishName(commonTravelers.getEnglishName());
                                        commonTravelersDtoVo.setDomesticPhone(commonTravelers.getDomesticPhone());
                                        commonTravelersDtoVo.setPassengerDocumentsVo(passengerDocumentsVo);
                                        commonTravelersDtoVo.setId(datum.getId());

                                        if (passengerDocuments != null && !passengerDocuments.equals(null) &&
                                                passengerDocuments.getCertificateNumcer().substring(0, 4).equals(datum.getIdenty().substring(0, 4)) &&
                                                passengerDocuments.getCertificateNumcer().substring(passengerDocuments.getCertificateNumcer().length()-3).equals(datum.getIdenty().substring(datum.getIdenty().length()-3))){
                                            switch (datum.getPhoneCheckStatus()){
                                                case "0":
                                                    commonTravelersDtoVo.setVerification("true");
                                                    break;
                                                case "1":
                                                    commonTravelersDtoVo.setVerification("false");
                                                    break;
                                                default:
                                                    commonTravelersDtoVo.setVerification("pendingReview");
                                                    break;
                                            }

                                            switch (datum.getCheckStatus()){
                                                case "0":
                                                    commonTravelersDtoVo.setVerified("true");
                                                    break;
                                                case "1":
                                                    commonTravelersDtoVo.setVerified("false");
                                                    break;
                                                default:
                                                    commonTravelersDtoVo.setVerified("pendingReview");
                                                    break;
                                            }
                                        }


                                        commonTravelersDtoVo.setTicketType(commonTravelers.getTicketType());
                                        if (phone.equals(commonTravelers.getDomesticPhone())){
                                            commonTravelersDtoVo.setMyself("true");
                                        }
                                        else {
                                            commonTravelersDtoVo.setMyself("false");
                                        }
                                        commonTravelersDtoVoList.add(commonTravelersDtoVo);
                                    }
                                }
                            }
                        }
                    }

                    sortVo.setLetter(letterList[i]);

                    if (commonTravelersDtoVoList != null && commonTravelersDtoVoList.size() > 0){
                        for (int count = 0 ; count < commonTravelersDtoVoList.size() ; count++){
                            for (int j = count + 1 ; j < commonTravelersDtoVoList.size() ; j++){
                                if (commonTravelersDtoVoList.get(count).getCommonTrvelersId().equals(commonTravelersDtoVoList.get(j).getCommonTrvelersId())){
                                    commonTravelersDtoVoList.remove(j);
                                    j--;
                                }
                            }
                        }
                    }

                    sortVo.setCommonTravelersDtoVoList(commonTravelersDtoVoList);
                    if (sortVo.getCommonTravelersDtoVoList().size() > 0){
                        sortVoList.add(sortVo);
                    }
                }
                letterDto.setSortVoList(sortVoList);
                return letterDto;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("参数传入错误");
        }
    }

    /**
     * 火车票-乘车人列表(CRM)
     * */
    @Override
    public List<CommonTravelersDtoVo> passengerListCrm(Long memberId, String phone) throws Exception {
         List<CommonTravelersDtoVo> commonTravelersDtoVoList = new ArrayList<>();

        if (memberId != null && memberId != 0){

            List<CommonTravelers> travelersList = commonTravelersMapper.passengerList(memberId);

            //获取会员12306账号信息
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", memberId);
            TrainAccountApi trainAccountApi = remoteTrainService.queryAccountIdCrm(map);

            TrContactQueryRequestApi contactQueryRequestApi = new TrContactQueryRequestApi();
            contactQueryRequestApi.trainAccount = trainAccountApi.getAccountId();
            contactQueryRequestApi.pass = trainAccountApi.getAccountPassword();

            TrContactQueryResponseApi trContactQueryResponseApi = remoteTrainService.contactQuerys(contactQueryRequestApi);

            if (!trContactQueryResponseApi.success){
                throw new Exception("未查询到12306乘车人信息");
            }

            if (travelersList != null && travelersList.size() > 0){

                for (CommonTravelers commonTravelers : travelersList) {
                    for (TrainContactsApi datum : trContactQueryResponseApi.data) {

                        if (commonTravelers.getIsDeletes().equals("false")){
                            CommonTravelersDtoVo commonTravelersDtoVo = new CommonTravelersDtoVo();
                            PassengerDocuments passengerDocuments = passengerDocumentsMapper.queryPassengerDocumentsByCommontrvelersId(commonTravelers.getCommonTrvelersId());

                            if (passengerDocuments.getCertificateNumcer()==null)
                            {
                                continue;
                            }
                            //数据库与12306乘车人比对
                            if (passengerDocuments != null && !passengerDocuments.equals(null) &&
                                    passengerDocuments.getCertificateNumcer().substring(0, 4).equals(datum.getIdenty().substring(0, 4)) &&
                                    passengerDocuments.getCertificateNumcer().substring(passengerDocuments.getCertificateNumcer().length()-3).equals(datum.getIdenty().substring(datum.getIdenty().length()-3)) &&
                                    commonTravelers.getChineseName().equals(datum.getName())){
                                commonTravelersDtoVo.setCertificateName(passengerDocuments.getCertificateName());
                                commonTravelersDtoVo.setCertificateNumcer(passengerDocuments.getCertificateNumcer());
                                commonTravelersDtoVo.setCertificateType(passengerDocuments.getCertificateType());
                                commonTravelersDtoVo.setCommontrvelersId(String.valueOf(commonTravelers.getCommonTrvelersId()));
                                commonTravelersDtoVo.setCertificateDate(passengerDocuments.getCertificateDate());

                                commonTravelersDtoVo.setCommonTrvelersId(commonTravelers.getCommonTrvelersId().toString());
                                commonTravelersDtoVo.setChineseName(commonTravelers.getChineseName());
                                commonTravelersDtoVo.setEnglishSurname(commonTravelers.getEnglishSurname());
                                commonTravelersDtoVo.setEnglishName(commonTravelers.getEnglishName());
                                commonTravelersDtoVo.setDomesticPhone(commonTravelers.getDomesticPhone());
                                commonTravelersDtoVo.setId(datum.getId());

                                if (passengerDocuments != null && !passengerDocuments.equals(null) &&
                                        passengerDocuments.getCertificateNumcer().substring(0, 4).equals(datum.getIdenty().substring(0, 4)) &&
                                        passengerDocuments.getCertificateNumcer().substring(passengerDocuments.getCertificateNumcer().length()-3).equals(datum.getIdenty().substring(datum.getIdenty().length()-3))){
                                    switch (datum.getPhoneCheckStatus()){
                                        case "0":
                                            commonTravelersDtoVo.setVerification("true");
                                            break;
                                        case "1":
                                            commonTravelersDtoVo.setVerification("false");
                                            break;
                                        default:
                                            commonTravelersDtoVo.setVerification("pendingReview");
                                            break;
                                    }

                                    switch (datum.getCheckStatus()){
                                        case "0":
                                            commonTravelersDtoVo.setVerified("true");
                                            break;
                                        case "1":
                                            commonTravelersDtoVo.setVerified("false");
                                            break;
                                        default:
                                            commonTravelersDtoVo.setVerified("pendingReview");
                                            break;
                                    }
                                }


                                commonTravelersDtoVo.setTicketType(commonTravelers.getTicketType());
                                if (phone.equals(commonTravelers.getDomesticPhone())){
                                    commonTravelersDtoVo.setMyself("true");
                                }
                                else {
                                    commonTravelersDtoVo.setMyself("false");
                                }
                                commonTravelersDtoVoList.add(commonTravelersDtoVo);
                            }
                        }
                    }
                }

                if (commonTravelersDtoVoList != null && commonTravelersDtoVoList.size() > 0){
                    for (int count = 0 ; count < commonTravelersDtoVoList.size() ; count++){
                        for (int j = count + 1 ; j < commonTravelersDtoVoList.size() ; j++){
                            if (commonTravelersDtoVoList.get(count).getCommonTrvelersId().equals(commonTravelersDtoVoList.get(j).getCommonTrvelersId())){
                                commonTravelersDtoVoList.remove(j);
                                j--;
                            }
                        }
                    }
                }
                return commonTravelersDtoVoList;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("参数传入错误");
        }
    }

    /**
     * 火车票-乘车人详细信息
     * */
    @Override
    public CommonTravelersDetailsVo passengerDetails(String commonTrvelersId, Customer customer) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        CommonTravelersDetailsVo commonTravelersDetailsVo = new CommonTravelersDetailsVo();
        Contacts contacts = new Contacts();

        //获取12306账号信息
        Customeraccount customeraccount = customeraccountService.queryAccountIdAndAccountPassword(customer.getCustomerId(), CustomerConstants.trianAccount.getValue());
        if (customeraccount.getAccountId() != null && !customeraccount.getAccountId().equals("") &&
                customeraccount.getAccountPassword() != null && !customeraccount.getAccountPassword().equals("")){
            commonTravelersDetailsVo.setTrainAccount(customeraccount.getAccountId());
            commonTravelersDetailsVo.setPass(customeraccount.getAccountPassword());
        }
        else {
            throw new Exception("未查到该会员12306账号信息");
        }

        CommonTravelers commonTravelers = commonTravelersMapper.passengerDetails(Long.valueOf(commonTrvelersId));
        if (commonTravelers != null && !commonTravelers.equals("")){
            contacts.setName(commonTravelers.getChineseName());
            contacts.setPersonType(commonTravelers.getTicketType());
            contacts.setPhone(commonTravelers.getDomesticPhone());
            contacts.setSex(commonTravelers.getGender());

            contacts.setCommonTrvelersId(commonTravelers.getCommonTrvelersId().toString());
            if (commonTravelers.getDomesticPhone().equals(customer.getContractPhoneOne())){
                contacts.setMyself("true");
            }
            else {
                contacts.setMyself("false");
            }
        }
        else {
            throw new Exception("未获取到乘车人信息");
        }

        //获取乘车人证件信息
        PassengerDocuments passengerDocuments = passengerDocumentsMapper.queryPassengerDocumentsByCommontrvelersId(commonTravelers.getCommonTrvelersId());
        if (passengerDocuments != null && !passengerDocuments.equals("")){
            contacts.setIdentyType(passengerDocuments.getCertificateType());
            contacts.setIdenty(passengerDocuments.getCertificateNumcer());
            contacts.setGatValidDateEnd(passengerDocuments.getCertificateDate());
            if (!passengerDocuments.getCertificateType().equals(EmHelper.CertificateType.ID_CARD) &&
                    !passengerDocuments.getCertificateType().equals(EmHelper.CertificateType.RPFHKMATR)){
                if (commonTravelers.getDateOfBirth() != null){
                    contacts.setBirthday(format.format(commonTravelers.getDateOfBirth()));
                }
                else {
                    throw new Exception("生日不能为空");
                }
            }
        }
        else {
            throw new Exception("未获取到乘车人证件信息");
        }

        //手机号核验
        TrContactQueryRequestApi request = new TrContactQueryRequestApi();
        request.trainAccount = customeraccount.getAccountId();
        request.pass = customeraccount.getAccountPassword();
        TrContactQueryResponseApi trContactQueryResponseApi = remoteTrainService.contactQuerys(request);
        for (TrainContactsApi datum : trContactQueryResponseApi.data) {
            if (passengerDocuments.getCertificateNumcer().substring(0, 4).equals(datum.getIdenty().substring(0, 4)) &&
                    passengerDocuments.getCertificateNumcer().substring(passengerDocuments.getCertificateNumcer().length() - 3).equals(datum.getIdenty().substring(datum.getIdenty().length() - 3))){
                switch (datum.getPhoneCheckStatus()){
                    case "0":
                        contacts.setVerification("true");
                        break;
                    case "1":
                        contacts.setVerification("false");
                        break;
                    default:
                        contacts.setVerification("pendingReview");
                        break;
                }

                switch (datum.getCheckStatus()){
                    case "0":
                        contacts.setVerified("true");
                        break;
                    case "1":
                        contacts.setVerified("false");
                        break;
                    default:
                        contacts.setVerified("pendingReview");
                        break;
                }
            }
        }

        boolean age = age(passengerDocuments.getCertificateType(), passengerDocuments.getCertificateNumcer(), format.format(commonTravelers.getDateOfBirth()));
        contacts.setSwitchPassengerType(String.valueOf(age));

        //国家信息
        if (commonTravelers.getNationId() != null && commonTravelers.getNationId() != 0){
            Nation nation = nationMapper.selectNationByNationId(commonTravelers.getNationId());
            if (nation != null && !nation.equals("")){
                contacts.setCountry(nation.getNationName());
                contacts.setCountryCode(nation.getCountryCode());
            }
            else {
                throw new Exception("未获取到乘车人国家信息");
            }
        }

        commonTravelersDetailsVo.setContacts(contacts);
        return commonTravelersDetailsVo;
    }

    /**
     * 火车票-修改乘车人信息
     * */
    @Override
    public int updatepassenger(CommonTravelers commonTravelers) throws Exception {
        if (commonTravelers != null && !commonTravelers.equals("")){
            int updatepassenger = commonTravelersMapper.updatepassenger(commonTravelers);
            if (updatepassenger > 0){
                return updatepassenger;
            }
            else {
                return 0;
            }
        }
        else {
            throw new Exception("参数不能为空");
        }
    }
    /**
     * 机票-乘客列表
     * */
    @Override
    public List<CommonTravelers> fileCommonTravelers(Long customerId) {
        List<CommonTravelers> commonTravelers = commonTravelersMapper.backSelectCommonTravelersBack(customerId);
        if (commonTravelers.size() > 0){
            return commonTravelers;
        }
        else {
            return null;
        }
    }

    /**
     * 后端——查询常用旅客信息
     * */
    @Override
    public List<CommonTravelersBack> backSelectCommonTravelersBack(Long customerId) throws Exception {
        if (customerId != null && customerId != 0){

            List<CommonTravelers> commonTravelersList = commonTravelersMapper.backSelectCommonTravelersBack(customerId);
            if (commonTravelersList != null && commonTravelersList.size() > 0){
                List<CommonTravelersBack> commonTravelersBackList = new ArrayList<>();
                for (CommonTravelers commonTravelers : commonTravelersList) {
                    if (commonTravelers.getIsDeletes().equals("false")){
                        CommonTravelersBack commonTravelersBack = new CommonTravelersBack();
                        commonTravelersBack.setTrvelersId(commonTravelers.getCommonTrvelersId().toString());//主键自增
                        commonTravelersBack.setChineseName(commonTravelers.getChineseName());//中文姓名
                        commonTravelersBack.setEnglishName(commonTravelers.getEnglishName()+" "+commonTravelers.getEnglishSurname());//英文姓名
                        commonTravelersBack.setGender(commonTravelers.getGender());//性别

                        Nation nation = nationMapper.selectNationByNationId(commonTravelers.getNationId());
                        if (nation != null){
                            commonTravelersBack.setNation(nation.getNationName());//国籍
                        }

                        PassengerDocuments passengerDocuments = passengerDocumentsMapper.queryPassengerDocumentsByCommontrvelersId(commonTravelers.getCommonTrvelersId());
                        if (passengerDocuments != null){
                            commonTravelersBack.passengerDocumentsId = passengerDocuments.getPassengerDocumentsId();
                            commonTravelersBack.certificateType = passengerDocuments.getCertificateType();
                            commonTravelersBack.certificateName = passengerDocuments.getCertificateName();
                            String certificateNumcer = passengerDocuments.getCertificateNumcer();
                            commonTravelersBack.certificateNumcer = certificateNumcer;
                            if (certificateNumcer != null && passengerDocuments.getCertificateType().equals(EmHelper.CertificateType.ID_CARD.getValue())) {
                                String birthday = certificateNumcer.substring(6, 10) + "-" + certificateNumcer.substring(10, 12) + "-" + certificateNumcer.substring(12, 14);
                                commonTravelersBack.birthday = birthday;
                            } else {
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                commonTravelersBack.birthday = dateFormat.format(commonTravelers.getDateOfBirth());
                            }

                            commonTravelersBack.certificateDate = passengerDocuments.getCertificateDate();
                            commonTravelersBack.phone = commonTravelers.getDomesticPhone();
                        }

//                        List<PassengerDocumentsBack> passengerDocumentsBackList = new ArrayList<>();
//                        if (passengerDocumentsList != null && passengerDocumentsList.size() > 0){
//                            for (PassengerDocuments passengerDocuments : passengerDocumentsList) {
//                                if (passengerDocuments.getIsDelete().equals("false")){
//                                    PassengerDocumentsBack passengerDocumentsBack = new PassengerDocumentsBack();
//                                    passengerDocumentsBack.setPassengerDocumentsId(passengerDocuments.getPassengerDocumentsId());//自增主键
//                                    passengerDocumentsBack.setCertificateType(passengerDocuments.getCertificateType());//证件类型
//                                    passengerDocumentsBack.setCertificateName(passengerDocuments.getCertificateName());//证件类型名称
//                                    String certificateNumcer = passengerDocuments.getCertificateNumcer();
//                                    passengerDocumentsBack.setCertificateNumcer(certificateNumcer);//证件号码
//                                    String birthday = certificateNumcer.substring(6, 10)+" "+certificateNumcer.substring(10, 12)+"-"+certificateNumcer.substring(12);
//                                    passengerDocumentsBack.setBirthday(birthday);//出生日期
//                                    passengerDocumentsBack.setCertificateDate(passengerDocuments.getCertificateDate());//证件有效期
//                                    passengerDocumentsBack.setPhone(commonTravelers.getDomesticPhone());//手机号
//                                    passengerDocumentsBackList.add(passengerDocumentsBack);
//                                }
//                            }
//                        }
//                        commonTravelersBack.setDocuments(passengerDocumentsBackList);//旅客证件
                        commonTravelersBackList.add(commonTravelersBack);
                    }
                }
                return commonTravelersBackList;
            }
            else {
                throw new Exception("未查询到旅客信息");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 后端——新增常用旅客
     * */
    @Transactional
    @Override
    public int backInsertCommonTravelersBack(CommonTravelersBack commonTravelersBack, Long customerId) throws Exception {
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        CommonTravelers commonTravelers = new CommonTravelers();
        PassengerDocuments passengerDocuments = new PassengerDocuments();

        List<CommonTravelers> travelers = commonTravelersMapper.queryCommonTravelersList(customerId);
        if (travelers != null && travelers.size() > 0) {
            for (CommonTravelers traveler : travelers) {
                if (traveler.getDocuments() != null) {
                    if (commonTravelersBack.getChineseName() != null && !commonTravelersBack.getChineseName().equals("")) {
                        if (commonTravelersBack.getChineseName().equals(traveler.getChineseName()) && commonTravelersBack.getDocuments().getCertificateNumcer().equals(traveler.getDocuments().getCertificateNumcer())) {
                            throw new Exception("旅客信息已存在");
                        }
                    } else {
                        int i = commonTravelersBack.getEnglishName().indexOf(" ");
                        if (commonTravelersBack.getEnglishName().substring(i+1).equals(traveler.getEnglishSurname()) && commonTravelersBack.getEnglishName().substring(0, i).equals(traveler.getEnglishName()) && commonTravelersBack.getDocuments().getCertificateNumcer().equals(traveler.getDocuments().getCertificateNumcer())) {
                            throw new Exception("旅客信息已存在");
                        }
                    }
                }
            }
        }
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils();
        long nextId = snowflakeUtils.nextId();
        commonTravelers.setCommonTrvelersId(nextId);//主键自增
        commonTravelers.setChineseName(commonTravelersBack.getChineseName());//中文姓名
        commonTravelers.setTicketType(commonTravelersBack.type);
        if (commonTravelersBack.getEnglishName() != null && !commonTravelersBack.getEnglishName().equals("")){
            int i = commonTravelersBack.getEnglishName().indexOf(" ");
            commonTravelers.setEnglishSurname(commonTravelersBack.getEnglishName().substring(i+1));//英文姓
            commonTravelers.setEnglishName(commonTravelersBack.getEnglishName().substring(0, i));//英文名
        }
        commonTravelers.setMemberId(customerId);//会员id
        commonTravelers.setGender(commonTravelersBack.getGender());//性别

        if (commonTravelersBack.getNation() != null && !commonTravelersBack.getNation().equals("")){
            Nation nation = nationMapper.selectNationByNationName(commonTravelersBack.getNation());
            commonTravelers.setNationId(nation.getNationId());//国籍id
        }
        else {
            throw new Exception("国籍不能为空");
        }

        if (commonTravelersBack.getDocuments() != null && commonTravelersBack.getDocuments().getCertificateNumcer() != null){
            if (commonTravelersBack.getDocuments().getBirthday() != null && !commonTravelersBack.getDocuments().getBirthday().equals(""))
                commonTravelers.setDateOfBirth(time.parse(commonTravelersBack.getDocuments().getBirthday()));//出生日期
            commonTravelers.setDomesticPhone(commonTravelersBack.getDocuments().getPhone());//手机号

            if (commonTravelersBack.getDocuments().getCertificateType() != null && !commonTravelersBack.getDocuments().getCertificateType().equals("")) {
                passengerDocuments.setCertificateType(commonTravelersBack.getDocuments().getCertificateType());//证件类型名称
                String certificateName = certificateName(commonTravelersBack.getDocuments().getCertificateType());
                passengerDocuments.setCertificateName(certificateName);
            } else {
                throw new Exception("证件类型不能为空");
            }
            passengerDocuments.setCertificateNumcer(commonTravelersBack.getDocuments().getCertificateNumcer());//证件号码
            passengerDocuments.setCertificateDate(commonTravelersBack.getDocuments().getCertificateDate());//证件有效期
        }
        else {
            throw new Exception("证件不能为空");
        }

        int insertCommonTravelers = commonTravelersMapper.backInsertCommonTravelers(commonTravelers);
        if (insertCommonTravelers > 0){
            passengerDocuments.setCommontrvelersId(commonTravelers.getCommonTrvelersId());//常用旅客id
            int i = passengerDocumentsMapper.backInsertPassengerDocuments(passengerDocuments);
            if (i > 0){
                return 1;
            }
            else {
                throw new Exception("证件信息新增失败");
            }
        }
        else {
            throw new Exception("常用旅客信息新增失败");
        }
    }

    /**
     * 获取证件类型
     * */
    public String certificateName(String certificateType){
        if (certificateType.equals(EmHelper.CertificateType.ID_CARD.getValue())) {
            certificateType = "身份证";
        } else if (certificateType.equals(EmHelper.CertificateType.MILITARY_ID.getValue())) {
            certificateType = "军人证";
        } else if (certificateType.equals(EmHelper.CertificateType.PASSPORT.getValue())) {
            certificateType = "护照";
        } else if (certificateType.equals(EmHelper.CertificateType.MTPFHKAMR.getValue())) {
            certificateType = "港澳居民来往内地通行证";
        } else if (certificateType.equals(EmHelper.CertificateType.MTPFTR.getValue())) {
            certificateType = "台湾居民来往大陆通行证";
        } else if (certificateType.equals(EmHelper.CertificateType.RPFHKMATR.getValue())) {
            certificateType = "港澳台居民居住证";
        } else if (certificateType.equals(EmHelper.CertificateType.PRICFF.getValue())) {
            certificateType = "外国人永久居留身份证";
        } else if (certificateType.equals(EmHelper.CertificateType.HKAMP.getValue())) {
            certificateType = "港澳通行证";
        } else if (certificateType.equals(EmHelper.CertificateType.ACCOUNT_BOOK.getValue())) {
            certificateType = "户口本";
        } else if (certificateType.equals(EmHelper.CertificateType.BIRTH_CERTIFICATE.getValue())) {
            certificateType = "出生证明";
        } else if (certificateType.equals(EmHelper.CertificateType.TAIWAN_PASS.getValue())) {
            certificateType = "台湾通行证";
        }
        return certificateType;
    }

    /**
     * 后端——修改常用旅客
     * */
    @Transactional
    @Override
    public int backUpdateCommonTravelers(CommonTravelersBack commonTravelersBack, Long customerId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        CommonTravelers commonTravelers = new CommonTravelers();
        commonTravelers.setCommonTrvelersId(commonTravelersBack.getCommonTrvelersId());
        commonTravelers.setChineseName(commonTravelersBack.getChineseName());
        if (commonTravelersBack.getEnglishName() != null && !commonTravelersBack.getEnglishName().equals("")){
            int i = commonTravelersBack.getEnglishName().indexOf(" ");
            if (i > 0){
                commonTravelers.setEnglishSurname(commonTravelersBack.getEnglishName().substring(i+1));//英文姓
                commonTravelers.setEnglishName(commonTravelersBack.getEnglishName().substring(0, i));//英文名
            }
            else {
                throw new Exception("英文名格式错误，例：boyang li");
            }
        }
        commonTravelers.setGender(commonTravelersBack.getGender());
        if (commonTravelersBack.getDocuments() != null && commonTravelersBack.getDocuments().getCertificateNumcer() != null){
            if (commonTravelersBack.getDocuments().getBirthday() != null && !commonTravelersBack.getDocuments().getBirthday().equals("")){
                try {
                    commonTravelers.setDateOfBirth(format.parse(commonTravelersBack.getDocuments().getBirthday()));
                } catch (Exception e){
                    throw new Exception("日期转换错误");
                }
                commonTravelers.setDomesticPhone(commonTravelersBack.getDocuments().getPhone());
            }
        }

        commonTravelers.setMemberId(customerId);
        if (commonTravelersBack.getNation() != null && !commonTravelersBack.getNation().equals("")){
            Nation nation = nationMapper.selectNationByNationName(commonTravelersBack.getNation());
            commonTravelers.setNationId(nation.getNationId());
        }
        int i = commonTravelersMapper.backUpdateCommonTravelers(commonTravelers);
        if (i > 0){
            return 1;
        }
        throw new Exception("修改失败");
    }

    /**
     * 后端——删除常用旅客证件信息
     * */
    @Transactional
    @Override
    public int backDeletePassengerDocuments(Long commontrvelersId) throws Exception {
        if (commontrvelersId != null && commontrvelersId != 0){
            int i = commonTravelersMapper.backDeleteCommonTravelers(commontrvelersId);
            if (i > 0){
                int documents = passengerDocumentsMapper.backDeletePassengerDocuments(commontrvelersId);
                if (documents > 0){
                    return 1;
                }
                else {
                    throw new Exception("删除失败");
                }
            }
            else {
                throw new Exception("删除失败");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 后端——修改常用旅客证件信息
     * */
    @Override
    public int backUpdatePassengerDocuments(@RequestBody PassengerDocuments passengerDocuments) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (passengerDocuments.getCertificateName() != null){
            String certificateType = certificateName(passengerDocuments.getCertificateName());
            passengerDocuments.setCertificateType(certificateType);
        }
        if (passengerDocuments.getCertificateDate() != null && !passengerDocuments.getCertificateDate().equals("")){
            try {
                Date date = format.parse(format.format(new Date()));
                Date time = format.parse(passengerDocuments.getCertificateDate());
                if (date.compareTo(time) < 0){
                    passengerDocuments.setValidPeriod("true");
                }
                else {
                    passengerDocuments.setValidPeriod("false");
                }
            } catch (Exception e){
                throw new Exception("时间转换错误");
            }
        }
        else {
            throw new Exception("证件有效期不能为空");
        }
        int documents = passengerDocumentsMapper.backUpdatePassengerDocuments(passengerDocuments);
        if (documents > 0){
            return 1;
        }
        else {
            throw new Exception("修改失败");
        }
    }

    /**
     * 后端——查询待修改的旅客证件信息
     * */
    @Override
    public CommonTravelersBack backSelectDocumentsById(Long passengerDocumentsId) throws Exception {
        if (passengerDocumentsId != null && passengerDocumentsId != 0){
            CommonTravelersBack commonTravelersBack = new CommonTravelersBack();
            PassengerDocuments passengerDocuments = passengerDocumentsMapper.backSelectDocumentsById(passengerDocumentsId);
            if (passengerDocuments != null){
                PassengerDocumentsBack passengerDocumentsBack = new PassengerDocumentsBack();
                passengerDocumentsBack.setPassengerDocumentsId(passengerDocuments.getPassengerDocumentsId());
                passengerDocumentsBack.setCertificateName(passengerDocuments.getCertificateName());
                passengerDocumentsBack.setCertificateNumcer(passengerDocuments.getCertificateNumcer());
                passengerDocumentsBack.setCertificateType(passengerDocuments.getCertificateType());
                CommonTravelers commonTravelers = commonTravelersMapper.backSelectTravelerById(passengerDocuments.getCommontrvelersId());
                if (commonTravelers != null){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    passengerDocumentsBack.setBirthday(format.format(commonTravelers.getDateOfBirth()));
                    passengerDocumentsBack.setPhone(commonTravelers.getDomesticPhone());
                    commonTravelersBack.setCommonTrvelersId(commonTravelers.getCommonTrvelersId());
                    if (commonTravelers.getChineseName() != null && !commonTravelers.getChineseName().equals("")){
                        commonTravelersBack.setChineseName(commonTravelers.getChineseName());
                    }
                    if (commonTravelers.getEnglishSurname() != null && !commonTravelers.getEnglishSurname().equals("") &&
                            commonTravelers.getEnglishName() != null && !commonTravelers.getEnglishName().equals("")){
                        commonTravelersBack.setEnglishName(commonTravelers.getEnglishName() + " " + commonTravelers.getEnglishSurname());
                    }
                    commonTravelersBack.setGender(commonTravelers.getGender());
                    Nation nation = nationMapper.selectNationByNationId(commonTravelers.getNationId());
                    if (nation != null){
                        commonTravelersBack.setNation(nation.getNationName());
                    }
                }
                passengerDocumentsBack.setCertificateDate(passengerDocuments.getCertificateDate());
                commonTravelersBack.setDocuments(passengerDocumentsBack);
                return commonTravelersBack;
            }
            else {
                throw new Exception("未查到数据");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 门票旅客列表
     * */
    @Override
    public Map<String, List<Map<String, Object>>> ticketsTravelerList(HttpServletRequest request) {
        Customer customer = loginService.getLoginCustomer(request);
        List<CommonTravelers> commonTravelers = commonTravelersMapper.backSelectCommonTravelersBack(customer.getCustomerId());

        List<Map<String, Object>> mapList = new ArrayList<>();

        for (CommonTravelers commonTraveler : commonTravelers) {
            Map<String, Object> map = new HashMap<>();

            commonTraveler.setTrvelersId(commonTraveler.getCommonTrvelersId().toString());
            map.put("id", commonTraveler.getTrvelersId());
            map.put("name", commonTraveler.getChineseName());
            map.put("tel", commonTraveler.getDomesticPhone());

            PassengerDocuments passengerDocuments = passengerDocumentsMapper.queryPassengerDocumentsByCommontrvelersId(commonTraveler.getCommonTrvelersId());

            map.put("address", passengerDocuments.getCertificateNumcer());
            mapList.add(map);
        }

        mapList.forEach(item -> {
            String letter = Pinyin4jUtil.getFirstLetter(item.get("name").toString());
//            if (item.get("cityname").toString().charAt(0) == '长') {
//                letter = "C";
//            }
//            String cityname = toPinyin(item.get("cityname").toString());
            item.put("initials", letter);
//            item.put("pinyin", cityname);
        });
        mapList.sort(Comparator.comparing(item -> item.get("initials").toString()));
        Map<String, List<Map<String, Object>>> map = mapList.stream().collect(Collectors.groupingBy(item -> item.get("initials").toString(), LinkedHashMap::new, Collectors.toCollection(ArrayList::new)));
        return map;
    }


    /**
     * 获取乘客证件信息
     * */
    public PassengerDocuments passengerDocuments(Long commontrvelersId){
        List<PassengerDocuments> documentsList = passengerDocumentsMapper.selectPassengerDocumentsByCommontrvelersId(commontrvelersId);

        if (documentsList != null && documentsList.size() > 0){
            int count = 0;
            int num = 0;
            PassengerDocuments passengerDocuments = new PassengerDocuments();
            for (int i = 0 ; i < documentsList.size() ; i++) {
                if (documentsList.get(i).getIsDelete().equals("false")){
                    if (documentsList.get(i).getCertificateType().equals(EmHelper.CertificateType.ID_CARD.getValue()) && count == 0){//获取乘客身份证
                        passengerDocuments = documentsList.get(i);
                        break;
                    }
                    else if (documentsList.get(i).getCertificateType().equals(EmHelper.CertificateType.PASSPORT.getValue()) && count == 1){//获取乘客护照
                        passengerDocuments = documentsList.get(i);
                        break;
                    }
                    else if (count == 2){
                        passengerDocuments = documentsList.get(i);
                        break;
                    }

                    if (i == documentsList.size()-1 && passengerDocuments != null){
                        if (num == 0){
                            count = 1;
                            i = 0;
                            num = 1;
                        }
                        else {
                            count = 2;
                            i = 0;
                        }
                    }
                }
            }
            return passengerDocuments;
        }
        else {
            return null;
        }
    }

    /**
     * 能否购买儿童票
     * */
    public boolean age(String certificateType, String passengerDocuments, String dateOfBirth) throws Exception {
        //证件类型与证件号不能为空
        if (certificateType != null && !certificateType.equals("") &&
                passengerDocuments != null && !passengerDocuments.equals("")){
            //证件类型不为身份证/港澳台居住证时，生日不能为空
            if (!certificateType.equals(EmHelper.CertificateType.ID_CARD) &&
                    !certificateType.equals(EmHelper.CertificateType.RPFHKMATR) &&
                    dateOfBirth != null && !dateOfBirth.equals("")){
                //身份证/港澳台居住证先获取生日信息
                if (certificateType.equals(EmHelper.CertificateType.ID_CARD) ||
                        certificateType.equals(EmHelper.CertificateType.RPFHKMATR)){
                    IDCardUtil idCardUtil = new IDCardUtil();
                    dateOfBirth = idCardUtil.getBirthFormatByIdCard(passengerDocuments);
                }

                try {
                    int age = age(dateOfBirth);
                    if (age < 18){
                        return true;
                    }
                    else {
                        return false;
                    }
                } catch (Throwable e) {
                    throw new Exception("年龄获取失败");
                }
            }
            else {
                throw new Exception("生日不能为空");
            }
        }
        else {
            throw new Exception("缺少证件相关信息");
        }
    }

    /**
     * 验证手机号格式
     * */
    public boolean checkPhoneValid(String phone) {
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    /**
     * 从证件号中获取年龄
     * */
    public int age(String dateOfBirth){
        Calendar currentDate = Calendar.getInstance();

        int bornYear = Integer.valueOf(dateOfBirth.substring(0, 4));
        int bornMonth = Integer.valueOf(dateOfBirth.substring(5, 7));
        int bornDay = Integer.valueOf(dateOfBirth.substring(8));

        int currentYear = currentDate.get(Calendar.YEAR);
        int currentMonth = currentDate.get(Calendar.MONTH) + 1;
        int currentDay = currentDate.get(Calendar.DATE);

        int age = currentYear - bornYear;
        if (bornMonth  > currentMonth ||
                (bornMonth == currentMonth && bornDay > currentDay)) {
            age--;
        }
        return age;
    }

    @Override
    public List<Nation> selectNationList() {
        return commonTravelersMapper.selectNationList();
    }
}
